package com.sedna.recipenote.framework.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sedna.recipenote.common.document.AppUser;
import com.sedna.recipenote.common.repository.AppUserRepository;
import com.sedna.recipenote.framework.value.UserValue;

@Service
public class AppUserDetailsService implements UserDetailsService {
	private Logger logger = Logger.getLogger(AppUserDetailsService.class);

	@Autowired
	private AppUserRepository appUserRepository;

	@Transactional
	public UserDetails loadUserByUsername(String userId)
			throws UsernameNotFoundException {
		logger.info("---------------- Inside loadByUserName 19832748174 ---------------- ");
		logger.info("USERID PASSED : " + userId);
		UserValue userValue = null;
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		grantedAuthorities.add(new SimpleGrantedAuthority("user"));

		AppUser appUser = null;

		appUser = appUserRepository.findByUserId(userId);
		userValue = new UserValue(appUser.getId(), appUser.getUserId(), appUser.getPassword(), grantedAuthorities, appUser.getFirstName(), appUser.getLastName());
		logger.info("USER VALUE RETRIEVED FROM DB:  " + userValue);
		logger.info("---------------- Inside loadByUserName ---------------- ");
		return userValue;
	}

/*	private List<GrantedAuthority> convertAppUserRolesToGrantedAuthorities(
			List<AppRole> appUserRoles) {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		for (AppRole appRole : appUserRoles) {
			grantedAuthorities.add(new SimpleGrantedAuthority(appRole.getName()));
		}
		return grantedAuthorities;
	}*/

}
